package com.raos.websocket.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * MyHandler 自定义 WebSocket 处理器 相当于 Controller
 * 创建一个 WebSocket 服务器的步骤：
 *     需要实现 WebSocketHandler 接口，或者继承 TextWebSocketHandler 或 BinaryWebSocketHandler 进行扩展
 *
 * 官方案例地址：https://docs.spring.io/spring-framework/docs/5.0.8.RELEASE/spring-framework-reference/web.html#websocket
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2021/10/16 9:04
 */
public class MyHandler extends TextWebSocketHandler {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        Map<String, String> map = JSON.parseObject(payload, HashMap.class);
        System.out.println(sdf.format(new Date()) + "=====接受到的数据" + map);
        System.out.println();
        session.sendMessage(new TextMessage("服务器返回收到的信息=" + payload + ", 响应时间: " + sdf.format(new Date())));
    }

}
